package com.zk;

import com.immomo.mcf.util.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: sun.hongliang
 * @create: 2019/10/10 11:52
 */
public class ZkFactory {
    private static CuratorFramework client = null;

    static {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (client != null) {
                    client.close();
                }
            }
        });
    }

    public static boolean loadKeeperConfigAndStart() {
        return loadKeeperConfigAndStart("zookeeper-config.properties");
    }

    public static boolean loadKeeperConfigAndStart(String configFileName) {
        Properties properties = new Properties();
        if (StringUtils.isEmpty(configFileName)) {
            configFileName = "zookeeper-config.properties";
        }
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(configFileName));

            String zookeeperConnectionString = properties.getProperty("connectString");
            int sessionTimeoutMs = Integer.valueOf(properties.getProperty("sessionTimeoutMs", "3000"));
            int connectionTimeoutMs = Integer.valueOf(properties.getProperty("connectionTimeoutMs", "3000"));
            int baseSleepTimeMs = Integer.valueOf(properties.getProperty("baseSleepTimeMs", "1000"));
            int maxRetries = Integer.valueOf(properties.getProperty("maxRetries", "3"));
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
            client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, sessionTimeoutMs, connectionTimeoutMs, retryPolicy);
            client.start();

            return true;
        } catch (IOException e) {
            throw new RuntimeException("Make sure " + configFileName + " correctly");
        }
    }

    public static CuratorFramework getZooKeeperClient() {
        return getZooKeeperClient("default");

    }

    public static CuratorFramework getZooKeeperClient(String namespace) {
        if (client == null) {
            loadKeeperConfigAndStart();
        }
        return client.usingNamespace(namespace);
    }

    public static void main(String[] args) throws Exception {
        CuratorFramework client = ZkFactory.getZooKeeperClient("nameSpace");
        ZkUtils.createIfNoNode(client, "/he/ff", "ff");
//        ZkUtils.replace(client,"/he/ee","nihao");
//
//        final NodeCache nodeCache = new NodeCache(client, "/he/ff");
//        nodeCache.start(true);
//
//
//        nodeCache.getListenable().addListener(new NodeCacheListener() {
//            @Override
//            public void nodeChanged() throws Exception {
//                ChildData c = nodeCache.getCurrentData();
//                System.out.println(new String(c.getData()));
//            }
//        });
//
//        ExecutorService executorService = Executors.newFixedThreadPool(2);
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("1");
//            }
//        });
    }
}
